package com.woniuxy.micropermissionserver.shiro;

import com.woniuxy.microcommonserver.bean.permission_hcz.Admin;
import com.woniuxy.micropermissionserver.adminmanage.service.IAdminService;
import com.woniuxy.micropermissionserver.redis.RedisCache;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;

public class LoginAndAuthRealm extends AuthorizingRealm {


    @Resource
    private IAdminService adminService;

    @Resource
    private RedisCache redisCache;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("开始认证！");
        //返回的当前主体令牌中的登录名
        String loginName = (String)authenticationToken.getPrincipal();
        Admin admin = adminService.login(loginName);
        if(admin == null){
            return null;
        }
        //如果用户存在，则将用户装配到Shiro 的 Session中
        redisCache.setCacheObject(admin.getLoginName(), admin);

        //所谓盐值加密，就是加密之后，再添加一部分内容，再加密
        // ByteSource 如果使用颜值加密需要创建ByteSource及对应的info对象
        ByteSource byteSource = new InitByteSource(loginName);


        //返回认证信息 (登录名，密码，域的名称)
        return new SimpleAuthenticationInfo(loginName, admin.getPassword(), byteSource, getName());
    }
}
